﻿using System;
using System.Globalization;
using System.Security.Principal;
using System.Threading;
using System.Web;
using OpenPhotoAlbum.BusinessLogics;

namespace OpenPhotoAlbum
{
	public class Global : System.Web.HttpApplication
	{
		protected void Application_BeginRequest(object sender, EventArgs e)
		{
			// Check whether the current visitor is blacklisted.
			CheckServiceRestriction();

			// Detect a previously stored cookie and restore
			// current culture if it is found.
			DetectAndRestoreLanguageCookie();
		}

		private void CheckServiceRestriction()
		{
			if (!ServiceManager.Instance.IsApproved())
			{
				Response.End();
			}
		}

		private void DetectAndRestoreLanguageCookie()
		{
			HttpRequest request = HttpContext.Current.Request;

			HttpCookie cookie = request.Cookies[Root.COOKIE_LANG];
			if (cookie != null)
			{
				CultureInfo ci = CultureInfo.CreateSpecificCulture(cookie.Value);
				Thread.CurrentThread.CurrentCulture = ci;
				Thread.CurrentThread.CurrentUICulture = ci;
			}
		}

		protected void Application_AuthenticateRequest(object sender, EventArgs e)
		{
			// Append role information to user's identity.

			GenericPrincipal user = HttpContext.Current.User as GenericPrincipal;

			if (user == null
				|| user.Identity == null
				|| !user.Identity.AuthenticationType.Equals("Forms", StringComparison.OrdinalIgnoreCase))
			{
				return;
			}

			if (BusinessLogics.UserManager.Instance.IsAdministrator(user.Identity.Name))
			{
				HttpContext.Current.User = new GenericPrincipal(
					user.Identity, new string[] { BusinessLogics.RoleNames.Administrator });
			}
			else if (BusinessLogics.UserManager.Instance.IsUser(user.Identity.Name))
			{
				HttpContext.Current.User = new GenericPrincipal(
					user.Identity, new string[] { BusinessLogics.RoleNames.CommonUser });
			}
			else
			{
				throw new RoleNotFoundException();
			}
		}
	}

	public class RoleNotFoundException : Exception { }
}